package com.yuchen.utils.springmvc;


import org.apache.commons.lang.time.DateFormatUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.CustomSerializerFactory;

import java.io.IOException;
import java.util.Date;

/**
 * User: qintao
 * Date: 14-3-17
 * Time: 下午5:12
 * Jackson 自定义规则  ,对日期进行转换
 */
public class MyJsonMapper extends ObjectMapper {
    public MyJsonMapper() {
        CustomSerializerFactory factory = new CustomSerializerFactory();
        factory.addGenericMapping(Date.class, new JsonSerializer<Date>() {
            @Override
            public void serialize(Date value, JsonGenerator jsonGenerator,
                                  SerializerProvider provider) throws IOException, JsonProcessingException {
                String name = value.getClass().getSimpleName();
                if ("Date".equals(name)) {
                    jsonGenerator.writeString(DateFormatUtils.format(value, "yyyy-MM-dd"));
                } else {
                    jsonGenerator.writeString(DateFormatUtils.format(value, "yyyy-MM-dd HH:mm:ss"));
                }
            }
        });
        this.setSerializerFactory(factory);
    }
}
